package com.mall.common.hessian.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mall.common.bean.Order;
import com.mall.common.bean.Pager;
import com.mall.common.exception.NoticeException;
import com.mall.common.hessian.ContentHessian;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.AdvertService;
import com.mall.common.service.ArticleCategoryService;
import com.mall.common.service.ArticleService;

@Service("contentHessian")
public class ContentHessianImpl extends BaseHessianImpl implements
		ContentHessian {
	@Resource private AdvertService advertService;
	@Resource private ArticleCategoryService articleCategoryService;
	@Resource private ArticleService articleService;

	@Override
	public String getAdvertBeans(String position, Integer num) {
		return listToJson(advertService.getAdverts(position, num));
	}

	@Override
	public String getArticlecategoryBeans(String parentCode, Integer num) {
		return listToJson(articleCategoryService.getArticleCategory(parentCode, num));
	}

	@Override
	public String getArticleBeans(Long categoryId, String categoryCode,
			Boolean isPublication, Boolean isTop, Boolean isRecommend,
			String orderBy, Integer num) {
		return listToJson(articleService.getAticles(categoryId, isPublication, isRecommend, isTop, orderBy, num, categoryCode));
	}

	@Override
	public String getArticleBean(Long articleId) {
		if(articleId == null){
			throw new NoticeException("文章不存在");
		}
		Finder finder = Finder.create("select new com.mall.common.bean.ArticleBean(bean) from ArticleDomain bean where bean.id =:articleId and bean.isPublication = true");
		finder.setParam("articleId", articleId);
		Object obj = finder.findUniqueByHQL();
		if(obj == null){
			throw new NoticeException("文章不存在");
		}
		return objToJson(obj);
	}

	@Override
	public String getArticlePager(String categoryCode, Boolean isPublication,
			Integer page, Integer size, String order) {
		Finder finder = Finder.create("select new com.mall.common.bean.ArticleBean(bean) from ArticleDomain bean where bean.category.code like :code and bean.isPublication = :isPublication");
		finder.setParam("code", categoryCode + "%");
		finder.setParam("isPublication", isPublication);
		Pager pager = new Pager();
		if(page != null){
			pager.setPageNumber(page);
		}
		if(size != null){
			pager.setPageSize(size);
		}
		finder.setOrder(Order.desc(order));
		return objToJson(articleService.findByPagerForHessian(pager, finder));
	}

}
